#!/bin/bash

# CDB Studio Build Script
set -e

echo "🚀 Building CDB Studio..."

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Function to print colored output
print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if Rust is installed
if ! command -v cargo &> /dev/null; then
    print_error "Cargo not found. Please install Rust: https://rustup.rs/"
    exit 1
fi

print_status "Rust version: $(rustc --version)"
print_status "Cargo version: $(cargo --version)"

# Clean previous builds
print_status "Cleaning previous builds..."
cargo clean

# Check formatting
print_status "Checking code formatting..."
if ! cargo fmt --check; then
    print_warning "Code formatting issues found. Running cargo fmt..."
    cargo fmt
fi

# Run clippy for linting
print_status "Running Clippy lints..."
cargo clippy --all-targets --all-features -- -D warnings

# Run tests
print_status "Running tests..."
cargo test --all

# Build in debug mode
print_status "Building in debug mode..."
cargo build --all

# Build in release mode
print_status "Building in release mode..."
cargo build --release --all

# Check binary size
if [ -f "target/release/cdb-studio" ]; then
    BINARY_SIZE=$(du -h target/release/cdb-studio | cut -f1)
    print_success "Release binary size: $BINARY_SIZE"
fi

# Run a quick smoke test
print_status "Running smoke test..."
if timeout 5s ./target/release/cdb-studio --help > /dev/null 2>&1; then
    print_success "Smoke test passed!"
else
    print_warning "Smoke test failed or timed out"
fi

print_success "Build completed successfully! 🎉"
print_status "Binary location: target/release/cdb-studio"
print_status "To run: ./target/release/cdb-studio"
